package org.example.web;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.example.vo.LoginProperties;
import org.example.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PowerIntercepto implements HandlerInterceptor {

    @Autowired
    LoginProperties loginProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO 权限访问控制  => 添加车辆
        if(request.getSession().getAttribute(loginProperties.getSessionKey()) == null){
            String accept = request.getHeader("Accept");
            if (accept.startsWith("application/json")) {
                //ajax 方法  =>  控制器方法  =>  返回json
                Result fail = Result.fail("请先登录系统");
                response.setContentType("application/json;charset=utf-8");
                new ObjectMapper().writeValue(response.getWriter(),fail);
            }else{
                //点击超链接 或者 表单提交  => 跳转方式
                //获取上下文路径
                String path = request.getContextPath();
                response.sendRedirect(path + "/login.html");
            }
            return false;
        }
        return true;
    }
}
